# 导入蓝图
import hashlib

from flask import Blueprint, render_template, flash, request, redirect, url_for, session
from flask_login import login_user, logout_user

from accounts.forms import RegisterForm, LoginForm
from models import User, db, UserInfo, UserLoginHistory

accounts=Blueprint('accounts',__name__,template_folder="templates",static_folder='../assets')


# 登录
@accounts.route('/login',methods=['GET','POST'])
def login():
    # 导入注册的表单
    form=LoginForm()
    # next_url搞不懂
    next_url=request.values.get('next',url_for('qa.index'))
    # 验证表单的信息
    if request.method=='POST':
        if form.validate_on_submit():
            print('登录成功')
            username=form.username.data
            password=form.password.data
            # 1.查找对应的用户
            password = hashlib.sha256(password.encode()).hexdigest()
            user = User.query.filter_by(username=username, password=password).first()
            # 2.登录用户
            # session['user_id']=user.id
            login_user(user)
            # 3.记录日志
            ip=request.remote_addr
            ua=request.headers.get('user-agent',None)
            user_login_obj=UserLoginHistory(user_id=user.id,username=username,ip=ip,ua=ua,login_type="web")
            db.session.add(user_login_obj)
            db.session.commit()
            # 4.跳转到首页

            flash(f"登录成功,欢迎{user.nickname}")
            return redirect(next_url)
        else:
            print(form.errors)
    else:
        print(11111)
    return render_template('login.html',form=form,next_url=next_url)

# 注册
@accounts.route('/register',methods=['GET','POST'])
def register():
    # 导入注册的表单
    form=RegisterForm()
    # 验证表单的信息
    if request.method=='POST':
        if form.validate_on_submit():
            user_result=form.user_register()
            if user_result:
                flash('注册成功，请登录','success')
                return redirect(url_for('accounts.login'))
            else:
                flash('注册失败，请稍后再试','danger')
                return render_template('register.html',form=form)
            # 获取表单信息
            # username=form.username.data
            # nickname=form.nickname.data
            # password=form.password.data
            # # 增加到db.session
            # #  新增user表
            # try:
            #     password = hashlib.sha256(password.encode()).hexdigest()
            #     user_obj=User(username=username,password=password,nickname=nickname)
            #     db.session.add(user_obj)
            #     # 新增userprofile表
            #     profile_obj=UserInfo(username=username,user=user_obj)
            #     db.session.add(profile_obj)
            #     db.session.commit()
            # except Exception as e:
            #     print(e)
            #     flash('注册失败，请稍后再试','danger')
            #     return render_template('register.html',form=form)
            # # 跳转成功的页面
            # flash('注册成功，请登录','success')
            # return redirect(url_for('accounts.login'))
        else:
            print("注册失败的跳转")
    return render_template('register.html',form=form)


# 个人中心
@accounts.route('/mine')
def mine():
    return render_template('mine.html')

# 退出登录
@accounts.route('/logout')
def logout():
    # 自定义登录的逻辑代码
    # session['user_id']
    # g.current_user=None
    logout_user()
    flash('欢迎下次再来','success')
    return redirect(url_for('accounts.login'))